<template>
  <div class="flex flex-wrap items-center gap-8px">
    <div v-for="(apartment, index) in productApartments" :key="apartment.id" class="select-box apartment-pic">
      <el-tooltip :content="apartment.name">
        <div class="relative h-full w-full">
          <el-image :src="apartment.thumbnailUrl" class="h-full w-full" />
            <el-icon class="del-icon"  v-show="!disabled"  @click="handleRemoveApartment(index)"><CloseBold /></el-icon>
        </div>
      </el-tooltip>
    </div>
    <el-tooltip content="选择公寓" v-if="canAdd">
      <div class="select-box" @click="openApartmentTableSelect">
        <el-icon>
          <plus />
        </el-icon>
      </div>
    </el-tooltip>
  </div>
  <!-- 公寓选择对话框（表格形式） -->
  <ApartmentTableSelect ref="apartmentTableSelectRef" :multiple="limit != 1" @change="handleApartmentSelected" />
</template>
<script lang="ts" setup>
import { listApartment } from '@/api/apartment/apartment/index';
import { ApartmentVO,ApartmentForm,ApartmentQuery } from '@/api/apartment/apartment/types';
import ApartmentTableSelect from '@/views/apartment/apartment/components/ApartmentTableSelect.vue';
import { propTypes } from '@/utils/propTypes';
import { isArray } from '@/utils/is';
import { oneOfType } from 'vue-types';

// 公寓列表，一般用于与公寓建立关系时使用
// 提供功能：展示公寓列表、添加公寓、移除公寓
defineOptions({ name: 'ApartmentSelect' });

// 查询参数
const initFormData: ApartmentForm = {
  id: undefined,
  name: undefined,
  thumbnail: undefined,
  introduction: undefined,
  districtId: undefined,
  districtName: undefined,
  cityId: undefined,
  cityName: undefined,
  provinceId: undefined,
  provinceName: undefined,
  addressDetail: undefined,
  latitude: undefined,
  longitude: undefined,
  phone: undefined,
  isRelease: undefined,
  facilityInfoIds: [],
  labelIds: [],
  area: [],
  graphBoList: []
};
const data = reactive<PageData<ApartmentForm, ApartmentQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 500,
    ids:undefined,
    name: undefined,
    introduction: undefined,
    districtId: undefined,
    districtName: undefined,
    cityId: undefined,
    cityName: undefined,
    provinceId: undefined,
    provinceName: undefined,
    addressDetail: undefined,
    latitude: undefined,
    longitude: undefined,
    phone: undefined,
    isRelease: undefined,
    facilityInfoIds: [],
    labelIds: [],
    area: [],
    params: {},
    delFlag: '0'
  },
  rules: {}
});

const { queryParams } = toRefs(data);

const props = defineProps({
  modelValue: oneOfType<number | string | Array<number>>([Number, Array]).isRequired,
  // 限制数量：默认不限制
  limit: propTypes.number.def(Number.MAX_VALUE),
  disabled: propTypes.bool.def(false)
});

// 计算是否可以添加
const canAdd = computed(() => {
  // 情况一：禁用时不可以添加
  if (props.disabled) return false;
  // 情况二：未指定限制数量时，可以添加
  if (!props.limit) return true;
  // 情况三：检查已添加数量是否小于限制数量
  return productApartments.value.length < props.limit;
});

// 公寓列表
const productApartments = ref<ApartmentVO[]>([]);

watch(
  () => props.modelValue,
  async () => {
    const ids = isArray(props.modelValue)
      ? // 情况一：多选
        props.modelValue
      : // 情况二：单选
        props.modelValue
        ? [props.modelValue]
        : [];
    // 不需要返显
    if (ids.length === 0) {
      productApartments.value = [];
      return;
    }
    // 只有商品发生变化之后，才去查询商品
    if (productApartments.value.length === 0 || productApartments.value.some((apartment) => !ids.includes(apartment.id!))) {
      queryParams.value.ids=ids;
      const res = await listApartment(queryParams.value);
      productApartments.value=res.rows;
    }
  },
  { immediate: true }
);

/** 商品表格选择对话框 */
const apartmentTableSelectRef = ref();
// 打开对话框
const openApartmentTableSelect = () => {
  apartmentTableSelectRef.value.open(productApartments.value);
};

/**
 * 选择商品后触发
 *
 * @param apartments 选中的商品列表
 */
const handleApartmentSelected = (apartments: ApartmentVO | ApartmentVO[]) => {
  productApartments.value = isArray(apartments) ? apartments : [apartments];
  emitApartmentChange();
};

/**
 * 删除商品
 *
 * @param index 商品索引
 */
const handleRemoveApartment = (index: number) => {
  productApartments.value.splice(index, 1);
  emitApartmentChange();
};
const emit = defineEmits(['update:modelValue', 'change']);
const emitApartmentChange = () => {
  if (props.limit === 1) {
    const apartment = productApartments.value.length > 0 ? productApartments.value[0] : null;
    emit('update:modelValue', apartment?.id || 0);
    emit('change', apartment);
  } else {
    emit(
      'update:modelValue',
      productApartments.value.map((apartment) => apartment.id)
    );
    emit('change', productApartments.value);
  }
};
</script>

<style lang="scss" scoped>
.select-box {
  display: flex;
  width: 60px;
  height: 60px;
  border: 1px dashed var(--el-border-color-darker);
  border-radius: 8px;
  align-items: center;
  justify-content: center;
}

.apartment-pic {
  position: relative;
}

.del-icon {
  position: absolute;
  top: -10px;
  right: -10px;
  z-index: 1;
  width: 20px !important;
  height: 20px !important;
}
</style>
